package it.free.maya.utilities;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * File utilities
 * @author Stefano Falconetti
 */
public class FileUtils {

	private static Logger logger = Logger.getLogger(FileUtils.class);
	
	/**
	 * Save the sitemap to be sent to the search engine or to be added to the robots.txt file
	 * @param content is the xml
	 * @param path is where the file has to be saved
	 */
	public static final String saveSitemap(String content, String path, String startURL){
		
		if(!(path.endsWith("/"))){
			path = path + "/";
		}
		
		path = path + startURL + ".sitemap." + System.currentTimeMillis() + ".xml";
		
		logger.info("Saving file on path [" + path + "]");
		
		File file = new File(path);
		
		FileWriter fileWriter = null;
			
		try{
			fileWriter = new FileWriter(file);
			fileWriter.write(content);
			fileWriter.flush();
			
		}catch(Exception exc){
			   logger.error("Unable to save file on path (1) [" + path + "]",  exc);
		}finally{
				 if(fileWriter != null){
					try{
						fileWriter.close();
					}catch(IOException exc){
						   logger.error("Unable to save file on path (2) [" + path + "]",  exc);
					}
				 }
		}
		logger.info("File saved on path [" + path + "]");
		return path;
	}
	
}
